import { defineStore } from 'pinia';
import { ElMessage } from 'element-plus';
import { encrypt } from '@/utils/encipher';

export default defineStore('favoritesStore', {
  state: () => ({
    // 收藏列表
    favoriteList: [],
  }),
  actions: {
    // 添加收藏
    addFavorite(song) {
      if (song.id == null) return;

      const existingSongIndex = this.favoriteList.findIndex(
        (item) => item.id === song.id
      );

      if (existingSongIndex > -1) {
        // 如果歌曲已存在，从收藏列表中移除
        this.favoriteList.splice(existingSongIndex, 1);
        ElMessage({
          message: '已取消收藏',
          type: 'success',
        });
        localStorage.setItem(
          'favoriteList',
          encrypt(JSON.stringify(this.favoriteList))
        );
      } else {
        // 如果歌曲不存在，则添加到收藏列表
        this.favoriteList.push({
          id: song.id,
          name: song.name,
          singers: song.singers,
        });
        ElMessage({
          message: '添加收藏成功',
          type: 'success',
        });
        localStorage.setItem(
          'favoriteList',
          encrypt(JSON.stringify(this.favoriteList))
        );
      }
    },
    // 收藏状态
    favoriteStatus(song) {
      const existingSongIndex = this.favoriteList.findIndex(
        (item) => item.id === song.id
      );
      if (existingSongIndex > -1) {
        return true;
      } else {
        return false;
      }
    },
    // 初始化收藏列表
    initFavoriteList(arr) {
      if (arr instanceof Array) {
        if (this.favoriteList.length === 0) {
          arr.forEach((item) => {
            this.favoriteList.push(item);
          });
        } else {
          for (let i = 0; i < arr.length; i++) {
            let found = false; // 标记是否找到相同的 id
            for (let j = 0; j < this.favoriteList.length; j++) {
              if (arr[i].id === this.favoriteList[j].id) {
                found = true;
                break; // 找到相同 id，中断内部循环
              }
            }
            if (!found) {
              this.favoriteList.push(arr[i]); // 只有在未找到相同 id 时添加元素
            }
          }
        }

        localStorage.setItem(
          'favoriteList',
          encrypt(JSON.stringify(this.favoriteList))
        );
      }
      return;
    },
  },
});
